package com.itheima.health.controller;

import com.itheima.health.common.GlobalConst;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.enums.PasswordTypeEnums;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author zhangmeng
 * @description
 * @date 2019/9/6
 **/
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    private static final String CURRENT_USER = "CURRENT_USER";
    @Autowired
    private UserService userService;

    @GetMapping("/getUsername")
    public Result getUsername(HttpServletRequest request) {
        String userName = (String) request.getSession().getAttribute(GlobalConst.USER_NAME);
        return new Result(true, userName);
    }
    /**
     * 根据用户名和密码登录
     *
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(HttpServletRequest request, @RequestBody LoginParam param) {
        log.info("[登录]data:{}",param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //用户不存在或密码不匹配则登录失败
//        String password = DigestUtils.md5DigestAsHex(param.getPassword().getBytes());
        String password = param.getPassword();
        String usernameParam = param.getUsername(); //前端用户名
        //用户不存在或密码不匹配则登录失败
        //用户拥有的权限字段集合
        List<String> PermissionkeyWordList = findPermissionFiledByUser(user);
        if (null == user ) {
            log.info("[登录]失败,该账户不存在，user:{}",usernameParam);
            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //用户存在,开始比对密码
        String userPassword = user.getPassword();
        //md5加密方式
        if (userPassword.startsWith(PasswordTypeEnums.MD5_TYPE.getValue())) {
            String salt = PasswordTypeEnums.MD5_SALT.getValue();
            String md5PasswordParam = PasswordTypeEnums.MD5_TYPE.getValue()+DigestUtils.md5DigestAsHex((password+salt).getBytes());
            log.info("加密密码:{}",md5PasswordParam);
            if (!md5PasswordParam.equals(userPassword)){
                log.info("[登录]失败,密码输入错误，user:{}",usernameParam);
                return new Result(false, MessageConst.LOGIN_FAIL);
            }
            //用户登录成功
            log.info("[登录]成功，user:{}",usernameParam);
            request.getSession().setAttribute(GlobalConst.USER_PERMISSION, PermissionkeyWordList);
            request.getSession().setAttribute(GlobalConst.USER_NAME,usernameParam);
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }
        //bcrypt加密方式
        if (userPassword.startsWith(PasswordTypeEnums.BCRYPT_TYPE.getValue())) {
            String bcryPasswordParam = PasswordTypeEnums.BCRYPT_TYPE.getValue()+ BCrypt.hashpw(password,BCrypt.gensalt());
            log.info("加密密码:{}",bcryPasswordParam);
            if (!BCrypt.checkpw(password,userPassword.substring(8))){
                log.info("[登录]失败,密码输入错误，user:{}",usernameParam);
                return new Result(false, MessageConst.LOGIN_FAIL);
            }
            //用户登录成功
            log.info("[登录]成功，user:{}",usernameParam);
            request.getSession().setAttribute(GlobalConst.USER_PERMISSION, PermissionkeyWordList);
            request.getSession().setAttribute(GlobalConst.USER_NAME,usernameParam);
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }
        //两种加密都匹配不上直接无法登陆
        log.info("[登录]失败，user:{}",usernameParam);
        return new Result(false, MessageConst.LOGIN_FAIL);
    }
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        request.getSession().invalidate();
        return new Result(true, MessageConst.ACTION_SUCCESS);
    }

    /**
     * 得到用户又有权限字段
     * @param user
     * @return
     */
    public List<String> findPermissionFiledByUser(User user){
        int userId = user.getId();
        return userService.findPermission(userId);
    }
}
